<template>
  <view class="order-center">
    <view class="order-center-container">
      <up-tabs
        :list="orderTabDict"
        :lineWidth="`25% - ${rpx2px(22)}px`"
        :line-height="rpx2px(11)"
        @change="handleOrderTabClick"
        :activeStyle="{
          color: '#303133',
          fontWeight: 'bold',
          transform: 'scale(1.05)',
        }"
      />
      <view class="list" v-if="orderListData.length > 0">
        <order-item
          v-for="(item, index) in orderListData"
          :key="index"
          :order-item="item"
          :show-check-box="item.showCheckBox"
          @checked-change="orderCheckedChange"
          @tap="toOrderDetail(item)"
        />
        <view class="tail" v-if="orderListData.length !== 0">
          {{ tailText }}
        </view>
        <!-- <up-list @scrolltolower="scrollToLower">
          <up-list-item v-for="(item, index) in orderListData" :key="index">
            <order-item
              :order-item="item"
              :show-check-box="item.showCheckBox"
              @checked-change="orderCheckedChange"
              @tap="toOrderDetail(item)"
            />
          </up-list-item>
        </up-list> -->
      </view>
      <none-data v-else />

      <view class="fixed-btn" v-if="showPayBtn">
        <up-button
          class="fixed-btn-pay"
          shape="circle"
          text="去支付"
          color="linear-gradient(to right, #FF934C, #FC686F)"
          @tap="handlePayBtnClick"
        />
      </view>

      <view class="popup-pay">
        <up-popup
          :show="payPopupDisabled"
          closeOnClickOverlay
          @close="handlePayPopupClose"
        >
          <view class="popup-pay__title"> 收银台 </view>
          <view class="popup-pay__desc">
            <view class="popup-pay__desc-detail">
              <text class="popup-pay__desc-detail-label"> 应付金额 </text>
              <text class="popup-pay__desc-detail-value">
                ¥ {{ checkedOrder.money }}元
              </text>
            </view>
          </view>
          <up-cell-group :border="false">
            <up-cell v-for="(item, idx) in payWayList" :key="idx">
              <template #title>
                <view class="u-slot-title">
                  <image class="pay-way__img" :src="item.payWayPrefixIconUrl" />
                </view>
                <view class="pay-way__name">
                  <text class="pay-way__name-title">{{ item.payWayName }}</text>
                  <text class="pay-way__name-desc">{{ item.desc }}</text>
                </view>
              </template>
              <template #value>
                <image
                  v-if="item.isChecked"
                  class="pay-way__img is-checked"
                  :src="isCheckedImgUrl"
                />
                <image
                  v-else
                  class="pay-way__img"
                  :src="notCheckedImgUrl"
                  @tap="handleCheckedPayWay(item)"
                />
              </template>
            </up-cell>
          </up-cell-group>

          <view class="popup-pay__btn-group">
            <up-button
              class="btn__pay"
              shape="circle"
              :text="`立即支付¥ ${checkedOrder.money} 元`"
              :disabled="payWayList.every((way) => !way.isChecked)"
              color="linear-gradient(to right, #FF934C, #FC686F)"
              @tap="handlePayForWithWayBtnClick"
            />
            <up-button
              class="btn__later-pay"
              plain
              shape="circle"
              text="稍后支付"
              type="warning"
              iconColor="linear-gradient(to right, #FF934C, #FC686F)"
              @tap="handleLaterPayBtnClick"
            />
          </view>
        </up-popup>
      </view>
    </view>
  </view>
</template>
<script setup>
import { ref, inject } from "vue";
import orderItem from "../../components/order-item/order-item.vue";
import { getCurrentPagesTotal, rpx2px } from "@/utils/utils";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
import {
  getLeaseOrderListApi,
  getLeaseOrderMsgCountApi,
  getUserHouseOrderListApi,
  userCancelPayLeaseOrderAPi,
  userPayLeaseOrderApi,
} from "@/package_kuafu_apartment/pages/api/order";
import { customNav } from "@/utils/customNav";
const orderTabDict = ref([
  {
    name: "预订订单",
    value: 0,
    badge: { value: 0 },
  },
  {
    name: "租房订单",
    value: 1,
    badge: { value: 0 },
  },
  {
    name: "商超订单",
    value: 2,
    badge: { value: 0 },
  },
  {
    name: "生活订单",
    value: 3,
    badge: { value: 0 },
  },
  {
    name: "物业订单",
    value: 4,
    badge: { value: 0 },
  },
]);
const tailText = ref("");
const getBadgeData = async () => {
  const res = await getLeaseOrderMsgCountApi();
  const { code, data } = res;
  if (code === 200) {
    const { reserveTotal, leaseTotal } = data;
    orderTabDict.value[0].badge.value = reserveTotal;
    orderTabDict.value[1].badge.value = leaseTotal;
  }
};

// 订单数据列表
const orderListData = ref([]);

// 预订订单状态字典
const reserveOrderStatusDict = {
  0: {
    text: "审核中",
    iconType: "warning",
  },
  1: {
    text: "未通过",
    iconType: "error",
  },
  2: {
    text: "待支付",
    iconType: "warning",
  },
  3: {
    text: "已支付",
    iconType: "success",
  },
  4: {
    text: "已撤销",
    iconType: "info",
  },
  5: {
    text: "部分退款",
    iconType: "info",
  },
  6: {
    text: "全额退款",
    iconType: "info",
  },
  7: {
    text: "转线下",
    iconType: "info",
  },
  8: {
    text: "已签约",
    iconType: "success",
  },
  9: {
    text: "对公转账支付审核中",
    iconType: "warning",
  },
  10: {
    text: "对公转账退款审核中",
    iconType: "warning",
  },
  11: {
    text: "对公转账退款审核未通过",
    iconType: "error",
  },
  12: {
    text: "支付中",
    iconType: "warning",
  },
  13: {
    text: "对公转账支付审核未通过",
    iconType: "error",
  },
};

// 租房订单状态字典
const leaseOrderStatusDict = {
  0: {
    text: "待支付",
    iconType: "warning",
  },
  1: {
    text: "已支付",
    iconType: "success",
  },
  2: {
    text: "对公转账支付审核中",
    iconType: "warning",
  },
  3: {
    text: "对公转账审核不通过",
    iconType: "error",
  },
  4: {
    text: "支付中",
    iconType: "warning",
  },
  5: {
    text: "支付失败",
    iconType: "error",
  },
};
const showDotStatusInHouseOrderList = ["2", "11", "13"];
const showDotStatusInRentHoustList = ["0", "3", "5"];
/**
 * 分页和列表数据相关 start
 * @type {Ref<UnwrapRef<number>>}
 */
const curPage = ref(1);
const curPageSize = ref(10);
const listTotal = ref(0);
const getUserHouseOrderList = async () => {
  await uni.showLoading({
    title: "订单加载中...",
  });
  const params = {
    page: curPage.value,
    pageSize: curPageSize.value,
  };
  const res = await getUserHouseOrderListApi(params);
  const { code, data } = res;
  if (code === 200) {
    const { records, total } = data;
    listTotal.value = total;
    let list = records.map((order) => {
      return {
        orderId: order.id,
        tagText: reserveOrderStatusDict[order.checkStatus]?.text,
        tagType: reserveOrderStatusDict[order.checkStatus]?.iconType,
        orderItemName: order.smallHouseTypeName,
        orderItemPrice: order.totalMoney + "元",
        orderItemTime: order.updateTime,
        showDot: showDotStatusInHouseOrderList.includes(order.checkStatus),
        orderType: "预订订单",
        ...order,
      };
    });
    if (listTotal.value > curPageSize.value * curPage.value) {
      tailText.value = "下滑加载更多";
    } else {
      tailText.value = "没有更多内容";
    }
    orderListData.value.push(...list);
    uni.hideLoading();
  }
};

const getLeaseOrderDataList = async () => {
  await uni.showLoading({
    title: "订单加载中...",
  });
  const params = {
    page: curPage.value,
    pageSize: curPageSize.value,
  };
  const res = await getLeaseOrderListApi(params);
  const { code, data } = res || {};
  if (code === 200) {
    uni.hideLoading();
    const { records, total } = data || {};
    listTotal.value = total;
    let list = records?.map((order) => {
      return {
        orderId: order.orderId,
        tagText: leaseOrderStatusDict[order.payStatus]?.text,
        tagType: leaseOrderStatusDict[order.payStatus]?.iconType,
        orderItemName: order.houseType,
        orderItemPrice: order.houseRent + "元",
        orderItemTime: order.updateTime,
        orderType: "租房订单",
        showCheckBox: leaseOrderStatusDict[order.payStatus]?.text === "待支付",
        showDot: showDotStatusInRentHoustList.includes(order.payStatus),
        ...order,
      };
    });
    orderListData.value.push(...list);
  }
};

const curTabName = ref("");
const showPayBtn = ref(false);
const handleOrderTabClick = (item) => {
  orderListData.value = [];
  curPage.value = 1;
  showPayBtn.value = false;
  let tabName = item.name;
  console.log("item", item.name);
  console.log("tabName", tabName);
  curTabName.value = tabName;
  // if (tabName.includes('预订订单')){
  if (tabName == "预订订单") {
    getUserHouseOrderList();
    // } else if (tabName.includes('租房订单')) {
  } else if (tabName == "租房订单") {
    getLeaseOrderDataList();
  }
};

const orderCheckedChange = (val) => {
  console.log(val, "我");
  console.log(orderListData.value);
  showPayBtn.value = orderListData.value.some((item) => item.payChecked);
};

const scrollToLower = () => {
  console.log("到dole");
  if (listTotal.value > curPageSize.value * curPage.value) {
    curPage.value++;
    getUserHouseOrderList();
  }
};

const packageKuaFuPath = inject("packageKuaFuPath");
const toOrderDetail = (orderItem) => {
  switch (orderItem.orderType) {
    case "预订订单":
      customNav(
        `${packageKuaFuPath}/my/pages/order-detail/index?id=${orderItem.orderId}&orderType=${orderItem.orderType}`
      );
      break;
    case "租房订单":
      const orderDetailData = JSON.stringify(orderItem);
      customNav(
        `${packageKuaFuPath}/my/pages/order-detail/lease-order-detail?orderDetail=${orderDetailData}`
      );
      break;
    default:
      break;
  }
};

onShow(() => {
  getBadgeData();
  orderListData.value = [];
  if (curTabName.value.includes("预订订单")) {
    getUserHouseOrderList();
  } else if (curTabName.value.includes("租房订单")) {
    getLeaseOrderDataList();
  }
});

onLoad(() => {
  curTabName.value = "预订订单";
});

onReachBottom(() => {
  if (listTotal.value > curPageSize.value * curPage.value) {
    curPage.value++;
    getUserHouseOrderList();
  }
});
const checkedOrder = ref({});
const payPopupDisabled = ref(false); /* 支付弹窗显示控制 */

/**
 * 去支付按钮监听
 */
const handlePayBtnClick = () => {
  payPopupDisabled.value = true;
  checkedOrder.value.money = orderListData.value.reduce((acc, curr) => {
    if (curr.payChecked) {
      return acc + curr.allAmount;
    } else {
      return acc;
    }
  }, 0);
};

const handlePayPopupClose = () => {
  payPopupDisabled.value = false;
};

const imgUrlPrefix = inject("baseImgUrl");
const isCheckedImgUrl = `${imgUrlPrefix}2024-04-26/1714103545102组 4@2x.png`;
const notCheckedImgUrl = `${imgUrlPrefix}2024-04-26/1714103688260椭圆 586 拷贝@2x.png`;
const payWayList = ref([
  {
    payWayName: "微信支付",
    payWayPrefixIconUrl: `${imgUrlPrefix}2024-04-26/1714101755578weixin@2x.png`,
    desc: "亿万用户的选择，更快更安全",
    isChecked: false,
  },
  {
    payWayName: "对公账号",
    payWayPrefixIconUrl: `${imgUrlPrefix}2024-04-26/1714101841808gongduigongzhuanzhang@2x.png`,
    desc: "以公开、透明的态度，为您提供优质的对公开户服务",
    isChecked: false,
  },
]);

/**
 * 支付方式选择监听
 * @param item
 */
const handleCheckedPayWay = (item) => {
  payWayList.value.forEach((way) => {
    way.isChecked = way.payWayName === item.payWayName;
  });
};

/**
 * 稍后支付按钮监听
 */
const handleLaterPayBtnClick = () => {
  payPopupDisabled.value = false;
  payWayList.value.forEach((way) => {
    way.isChecked = false;
  });
};

/**
 * 确认支付按钮监听
 */
const handlePayForWithWayBtnClick = () => {
  if (payWayList.value.every((way) => !way.isChecked)) return;
  const way = payWayList.value.find((way) => way.isChecked).payWayName;
  switch (way) {
    case "微信支付":
      let payType = "";
      // #ifndef MP-WEIXIN
      payType = "1";
      // #endif
      // #ifdef MP-WEIXIN
      payType = "0";
      // #endif
      getOrderPayData(payType);
      break;
    case "对公账号":
      const orderId = checkedOrder.value.reserveId;
      const orderData = JSON.stringify(
        orderListData.value.filter((item) => item.payChecked)
      );
      customNav(
        `${packageKuaFuPath}/my/pages/order-detail/public-transfer?orderId=${orderId}&price=${checkedOrder.value.money}&payName=房屋租金&orderData=${orderData}`
      );
      break;
  }
};

/**
 * 获取支付数据
 * @returns {Promise<void>}
 */
const getOrderPayData = async (type) => {
  const params = orderListData.value.filter((order) => order.payChecked);
  params.forEach((item) => {
    item.payType = type;
  });
  const res = await userPayLeaseOrderApi(params);
  const { code, data } = res;
  if (code === 200) {
    // #ifndef MP-WEIXIN
    weChatAppPay(data); // 微信APP支付
    // #endif
    // #ifdef MP-WEIXIN
    toPay(data); //微信小程序支付
    // #endif
  }
};

/**
 * 唤起支付
 * @param payData
 */
const toPay = (payData) => {
  uni.requestPayment({
    provider: "wxpay",
    timeStamp: payData.timeStamp,
    nonceStr: payData.nonceStr,
    package: payData.prepayId,
    signType: payData.signType,
    paySign: payData.paySign,
    success: function (res) {
      console.log("success:" + JSON.stringify(res));
      uni.showToast({
        title: "支付成功",
        duration: 2000,
        success: () => {
          payPopupDisabled.value = false;
        },
      });
    },
    fail: function (err) {
      userCancelPayLeaseOrderAPi(
        orderListData.value.map((order) => {
          if (order.payChecked) {
            return order.orderId;
          }
        })
      );
      console.log("fail:" + JSON.stringify(err));
    },
  });
};

// 微信APP支付
const weChatAppPay = (payData) => {
  let params = {
    partnerId: payData.partnerId, //商户号
    prepayId: payData.prepayId, //预支付交易会话ID
    nonceStr: payData.nonceStr, //随机字符串
    timeStamp: payData.timeStamp, //时间戳
    sign: payData.paySign, //签名
  };
  window.mobile.jsCallPayWx(JSON.stringify(params));
};
</script>
<style scoped lang=less>
@import "./style/order-center";
</style>
